<script setup>
import { computed, nextTick, ref, watch, defineComponent, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import { getOptions } from '@/utils'
import UploadFile from '@/components/UploadFile/UploadFile.vue'
import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
import SysDep from '@/views/SystemManage/SysDep/SysDep.vue'
import { phoneRule } from '@/utils/checkRule.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => {}
  },
  faMenuSltOpt: {
    type: Array,
    default: () => []
  }
})

const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true
    }
  },
  render() {
    return this.vnodes
  }
})

// 弹窗标题
const title = computed(() => (props.curRow.machineId ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  useDescribe: '',
  workType: [],
  machineType: '',
  machineNo: '',
  machineName: '',
  currentLocation: '',
  machineStatus: '',
  machineImages: '',
  belongType: '',
  belongOrgId: '',
  belongOrgName: '',
  belongOrgPhone: '',
  checkInfo: '',
  remark: '',
  approveStatus: '',
  approveRemark: '',
  applyUserName: '',
  applyUserPhone: '',
  applyTime: '',
  applyRemark: '',
  checkInfoV1: '',
  checkInfoV2: '月',
  checkInfoV3: '',
  checkInfoV4: ''
})

const options = ref([])

//农机类型数据映射
const MachineTypeOptions = async () => {
  const option = getOptions('machine_type')
  options.value = option.map((item) => {
    return {
      value: item?.constValue,
      label: item?.constLabel
    }
  })
}

//根据农机类型和作业类型自动填入对应的用途描述
const useDescribe = computed(() => {
  const TypeOptions = options.value.find((item) => item.value === formData.value.machineType)
  if (TypeOptions && formData.value.workType.length > 0) {
    return `${TypeOptions.label}：${formData.value.workType.join(', ')}`
  }
  if (TypeOptions) {
    return `${TypeOptions.label}`
  }
  return ''
})

// 更新用途描述
watch(
  [() => formData.value.machineType, () => formData.value.workType],
  () => {
    if (!formData.value.machineId) {
      formData.value.useDescribe = useDescribe.value
    }
  },
  { deep: true }
)

// 新增动态获取作业类型选项的状态
const workTypeOptions = ref([])
const newWorkType = ref('')

//获取作业类型
const getWorkType = async (newType) => {
  try {
    const workTypes = await api.getMachinWorkType({ machineType: newType })
    workTypeOptions.value = workTypes.data.map((item) => {
      return {
        value: item.workType,
        label: item.workType,
        id: item.id
      }
    })
    formData.value.workType = workTypeOptions.value.map((option) => option.value)
  } catch (error) {
    console.log(error)
  }
}

// 监听农机类型的变化，动态更新作业类型选项
watch(
  () => formData.value.machineType,
  async (newType) => {
    if (newType) {
      getWorkType(newType)
      formData.value.workType = []
    } else {
      workTypeOptions.value = []
    }
  }
)

// 添加新作业类型的函数
const addNewWorkType = async () => {
  if (
    newWorkType.value &&
    !workTypeOptions.value.some((option) => option.label === newWorkType.value)
  ) {
    try {
      await api.addWorkType({
        workType: newWorkType.value,
        machineType: formData.value.machineType
      })
      getWorkType(formData.value.machineType)
    } finally {
      newWorkType.value = ''
    }
  } else {
    message.warning('该作业类型已存在或输入为空')
  }
}

//删除对应作业类型
const deleteWorkType = async (value) => {
  try {
    await api.delWorkType({ id: value })
    getWorkType(formData.value.machineType)
  } catch (error) {
    console.log(error)
  }
}

// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    // 按钮类型的父节点id为数组，需要特殊处理
    formData.value = { ...formData.value, ...val }
    if (val.machineId) {
      const { data } = await api.getMachinInfo({ id: val.machineId })
      formData.value = {
        ...formData.value,
        ...val,
        ...data,
        checkInfoV1: data.checkInfo.split(',')[0],
        checkInfoV2: data.checkInfo.split(',')[1],
        checkInfoV3: data.checkInfo.split(',')[2],
        checkInfoV4: data.checkInfo.split(',')[3],
        workType: data.workType ? data.workType.split(',') : []
      }
    }
  },
  { deep: true, immediate: true }
)
// 是否显示弹窗
const show = ref(false)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      useDescribe: '',
      workType: [],
      machineType: '',
      machineNo: '',
      machineName: '',
      currentLocation: '',
      machineStatus: '',
      machineImages: '',
      belongType: '',
      belongOrgId: '',
      belongOrgName: '',
      belongOrgPhone: '',
      checkInfo: '',
      remark: '',
      approveStatus: '',
      approveRemark: '',
      applyUserName: '',
      applyUserPhone: '',
      applyTime: '',
      applyRemark: '',
      checkInfoV1: '',
      checkInfoV2: '月',
      checkInfoV3: '',
      checkInfoV4: ''
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      checkInfo:
        info.checkInfoV1 + ',' + info.checkInfoV2 + ',' + info.checkInfoV3 + ',' + info.checkInfoV4,
      workType: info.workType.join(',')
    }
    await api.editMachin(params)
    message.success('编辑成功')
    show.value = false
    emits('reload')
  } finally {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 新增数据
const addItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      checkInfo:
        info.checkInfoV1 + ',' + info.checkInfoV2 + ',' + info.checkInfoV3 + ',' + info.checkInfoV4,
      workType: info.workType.join(',')
    }
    await api.addMachin(params)
    message.success('新增成功')
    show.value = false

    emits('reload')
  } finally {
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
  }
}
// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.machineId) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })

const fileChange = (key) => {
  if (formRef.value?.validateFields) {
    nextTick(() => {
      setTimeout(() => {
        formRef.value.validateFields([key])
      }, 0)
    })
  }
}

onMounted(() => {
  MachineTypeOptions()
})
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        label="农机名称"
        name="machineName"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.machineName" allowClear />
      </a-form-item>
      <a-form-item
        label="农机编号"
        name="machineNo"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.machineNo" allowClear />
      </a-form-item>
      <a-form-item
        label="农机类型"
        name="machineType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.machineType"
          :options="getOptions('machine_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item label="农机作业类型" name="workType" v-if="formData.machineType">
        <a-select
          v-model:value="formData.workType"
          :options="workTypeOptions"
          allowClear
          mode="multiple"
        >
          <template #option="{ label, id }">
            <div class="select-option">
              <span>{{ label }}</span>
              <span @click="deleteWorkType(id)">x</span>
            </div>
          </template>
          <template #dropdownRender="{ menuNode: menu }">
            <v-nodes :vnodes="menu" />
            <div>
              <div style="display: flex; gap: 8px; padding: 8px">
                <a-input v-model:value="newWorkType" placeholder="新增作业类型" style="flex: 1" />
                <a-button type="link" @click="addNewWorkType">添加</a-button>
              </div>
            </div>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item
        label="农机用途描述"
        name="useDescribe"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-textarea v-model:value="formData.useDescribe" show-count :maxlength="40" />
      </a-form-item>
      <a-form-item label="维保周期" required>
        <a-form-item label="" name="checkInfoV1" :rules="[{ required: true, message: '请输入' }]">
          <a-input-number
            :min="1"
            v-model:value="formData.checkInfoV1"
            allowClear
            style="width: 50%"
          />
        </a-form-item>
        <a-form-item label="" name="checkInfoV2" :rules="[{ required: true, message: '请输入' }]">
          <a-select
            v-model:value="formData.checkInfoV2"
            :options="[
              { label: '年', value: '年' },
              { label: '月', value: '月' }
            ]"
            style="width: 50%"
          ></a-select>
        </a-form-item>
        <a-form-item label="" name="checkInfoV3" :rules="[{ required: true, message: '请输入' }]">
          <a-input-number
            :min="1"
            v-model:value="formData.checkInfoV3"
            allowClear
            addonAfter="次"
            style="width: 50%"
          />
        </a-form-item>
        <a-form-item label="" name="checkInfoV4" :rules="[{ required: true, message: '请输入' }]">
          <a-textarea
            v-model:value="formData.checkInfoV4"
            allowClear
            style="width: 100%"
            placeholder="输入维保内容"
          />
        </a-form-item>
      </a-form-item>
      <a-form-item
        label="农机图片"
        name="machineImages"
        :rules="[{ required: true, message: '请' }]"
      >
        <a-form-item-rest>
          <UploadFile
            :limit="1"
            v-model="formData.machineImages"
            @update:modelValue="fileChange('machineImages')"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        label="农机归属"
        name="belongType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.belongType"
          :options="getOptions('belong_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <template v-if="formData.belongType === 2">
        <a-form-item
          label="归属人姓名"
          name="belongOrgName"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-input v-model:value="formData.belongOrgName" allowClear />
        </a-form-item>
        <a-form-item label="归属人电话" name="belongOrgPhone" :rules="phoneRule">
          <a-input v-model:value="formData.belongOrgPhone" allowClear />
        </a-form-item>
      </template>
      <template v-if="formData.belongType === 1">
        <a-form-item
          label="归属合作社"
          name="belongOrgId"
          :rules="[{ required: true, message: '请输入' }]"
        >
          <a-form-item-rest>
            <SltFromTable
              v-model="formData.belongOrgId"
              :component="SysDep"
              :fieldNames="{ name: 'name', id: 'id' }"
              :nameValue="formData.belongOrgName"
              :getRows="(e) => (formData.belongOrgName = e?.[0]?.name ?? '')"
            />
          </a-form-item-rest>
        </a-form-item>
      </template>
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="formData.remark" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<style scoped>
.select-option {
  display: flex;
  justify-content: space-between;

  span:nth-child(2) {
    padding: 0 5px;
    font-size: 15px;
    &:hover {
      color: #bfbfbf;
    }
  }
}
</style>

<style>
.ant-select-item-option-selected .ant-select-item-option-state {
  display: none;
}
</style>
